﻿/// <reference path="~/_external/jquery/v1/jquery.min.js" />
/// <reference path="~/_external/jquery/v1/jquery-migrate.min.js" />
/// <reference path="~/admin/ui/js/Conf.js" />
/// <reference path="~/admin/ui/js/lan_cn.js" />
/// <reference path="~/admin/ui/js/lan_extension.js" />

function TianvUtils() { return this; }
var Utils = new TianvUtils();

(function ($) {

    TianvUtils.prototype.getGuid = function () {
        /// <summary>生成GUID(全局统一标识符)，</summary>
        /// <returns type="String">GUID 的格式为"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"</returns>
        var guid = "";
        for (var i = 1; i <= 32; i++) {
            var n = Math.floor(Math.random() * 16.0).toString(16);
            guid += n;
            if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                guid += "-";
        }
        return guid;
    };

    TianvUtils.prototype.getSmallButton = function (node, useIcon, useText) {
        /// <summary>获取超链接</summary>
        /// <param name="node">json数据节点, 参考：{ href:'', target: '', alt: '', title: '', text: '', span: false, img: '', dbox: {}  }</param>
        /// <param name="useIcon">是否需要图标</param>
        /// <param name="useText">是否需要文字</param>

        var text = node.text? node.text: node.title;
        var img = node.icon? node.icon: node.img;

        var a_text = '<a href="' + node.href + '"';
        if (node.target) a_text += ' target="' + node.target + '"';
        if (node.alt) a_text += ' alt="' + node.alt + '"';
        if (node.title) a_text += ' title="' + node.title + '"';
        a_text += '>';
        if (useIcon) a_text += this.getIcon(img);
        if (useText) a_text +=  '<span>' + text + '</span>';
        a_text += '</a>';

        var a = $(a_text);
        if (node.dbox) {
            if (!node.dbox.icon)
                node.dbox['icon'] = node.icon;
            if (!node.dbox.title)
                node.dbox['title'] = node.title ? node.title : node.text;
            a.data('dbox', node.dbox);
            a.attr('target', 'dbox');
        }
        if( node.confirm ){
            a.data('confirm', node.confirm);
        }
        
        a.data('node', node);
        return a;
    };

    TianvUtils.prototype.getIcon = function (name) {
        /// <summary>获取图标</summary>
        /// <param name="name">图标名称</param>
        /// <returns type="String">图标对应Html代码， 参考内容：<img src="blank.gif" alt="" class="picon picon_{name}" /></returns>
        return '<img src="' + UI.BasePath + 'images/b16.gif" alt="" class="picon picon_' + name + '" />';
    };

    TianvUtils.prototype.isBoolean = function (data) {
        /// <summary>类型检测(严格): 是否布尔类型</summary>
        /// <param name="data">被检测内容</param>
        if (data === null) return false;
        return typeof (data) == 'boolean';
    }

    TianvUtils.prototype.isNumber = function (data) {
        /// <summary>类型检测(严格): 是否数字类型</summary>
        /// <param name="data">被检测内容</param>
        if (data === null) return false;
        return typeof (data) == 'number';
    }

    TianvUtils.prototype.isString = function (data) {
        /// <summary>类型检测(严格): 是否字符串类型</summary>
        /// <param name="data">被检测内容</param>
        if (data === null) return false;
        return typeof (data) == 'string';
    };

    TianvUtils.prototype.htmlEncode = function (str) {
        if (!Utils.isString(str)) return str;
        if (str.length <= 0) return str;

        return str
            .replace(/&/g, '&amp;')
            .replace(/\\/g, '&#092;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/'/g, '&#039;')
            .replace(/"/g, '&quot;')
            .replace(/\u00a9/g, '&copy;')
            .replace(/\u00ae/g, '&reg;');
    };

    TianvUtils.prototype.htmlDecode = function (str) {
        if (!Utils.isString(str)) return str;
        if (str.length <= 0) return str;

        return str
            .replace(/&amp;/g, '&')
            .replace(/&#092;/g, '\\')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&#039;/g, '\'')
            .replace(/&quot;/g, '"')
            .replace(/&copy;/g, '\u00a9')
            .replace(/&reg;/g, '\u00ae');
    };

    TianvUtils.prototype.stringFormat = function (str, args) {
        if (!Utils.isString(str)) return str;

        return str.replace(/\{(\d+)\}/g,
            function (m, i) {
                return args[i];
            });
    };

    TianvUtils.prototype.getText = function (name) {
        /// <summary>翻译</summary>
        /// <param name="name">被翻译内容, 参考格式：lan.Company.Name</param>
        if (!Utils.isString(name)) return name;
        else if (name.indexOf('lan.') != 0) return name;

        var names = name.substr(4).split('.');
        var str = lan;
        for (var i = 0; i < names.length; i++) {
            var temp = names[i];
            if (!temp) return '';
            str = str[temp];
            if (!str) return '';
        }
        return str;
    };

    TianvUtils.prototype.setText = function ($el) {
        /// <summary>自动翻译</summary>
        /// <param name="$el">待翻译文档</param>
        $el.find('[title]').each(function () {
            var $me = $(this);
            var title = $me.attr('title').toString();
            if (title.length <= 5 || title.indexOf('lan.') != 0) return;
            var text = Utils.getText(title);
            var nodeName = $me[0].nodeName.toLocaleLowerCase();

            if (nodeName == 'title') {
                document.title = text;
            } else if (nodeName == 'img') {
                $me.attr('title', text);
                return;
            } else {
                $me.html(text);
            }
            $me.removeAttr('title');
        });
    };

    TianvUtils.prototype.getAdminCodeFile = function (file) {
        /// <summary>获取代码文件地址</summary>
        /// <param name="file">相对地址(无扩展名): 参考格式：about/info</param>
        /// <returns type="String">代码的绝对地址， 参考内容：/admin/code/{file}.ashx</returns>
        return Conf.Paths.Admin + "code/" + file + Conf.CodeExtension;
    };

    TianvUtils.prototype.getModuleCodeFile = function (name, file) {
        /// <summary>获取模块代码文件地址</summary>
        /// <param name="name">模块名称</param>
        /// <param name="file">相对地址(无扩展名): 参考格式：info/view</param>
        /// <returns type="String">模块代码的绝对地址， 参考内容：/modules/{name}/admin/code/{file}.ashx</returns>
        return Conf.Paths.Module + name + "/admin/code/" + file + Conf.CodeExtension;
    };

    TianvUtils.prototype.getWidgetCodeFile = function (name, file) {
        /// <summary>获取组件代码文件地址</summary>
        /// <param name="name">组件名称</param>
        /// <param name="file">相对地址(无扩展名): 参考格式：info/view</param>
        /// <returns type="String">组件代码的绝对地址， 参考内容：/widgets/{name}/admin/code/{file}.ashx</returns>
        return Conf.Paths.Widget + name + "/admin/code/" + file + Conf.CodeExtension;
    };

    TianvUtils.prototype.getPluginCodeFile = function (name, file) {
        /// <summary>获取插件代码文件地址</summary>
        /// <param name="name">插件名称</param>
        /// <param name="file">相对地址(无扩展名): 参考格式：info/view</param>
        /// <returns type="String">插件代码的绝对地址， 参考内容：/plugins/{name}/admin/code/{file}.ashx</returns>
        return Conf.Paths.Plugin + name + "/admin/code/" + file + Conf.CodeExtension;
    };

    TianvUtils.prototype.getChannelCodeFile = function (name, file) {
        /// <summary>获取组件代码文件地址</summary>
        /// <param name="name">组件名称</param>
        /// <param name="file">相对地址(无扩展名): 参考格式：info/view</param>
        /// <returns type="String">组件代码的绝对地址， 参考内容：/widgets/{name}/admin/code/{file}.ashx</returns>
        return Conf.Paths.Channel + name + "/admin/code/" + file + Conf.CodeExtension;
    };

    var StyleSheets = new Array();
    TianvUtils.prototype.loadStyle = function (href) {
        /// <summary>加载样式</summary>
        /// <param name="href">样式文件地址</param>

        for (var i = 0; i < StyleSheets.length; i++) {
            if (StyleSheets[i] == href)
                return;
        }

        StyleSheets.push(href);

        var link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", href);
        document.getElementsByTagName("head")[0].appendChild(link);
    };

    
    TianvUtils.prototype.getDirs = function( url ){
        if( url.toLowerCase().indexOf('.html') == -1 )
            return null;

        var urls=[];
	    if( url.indexOf('://') == -1 ){
			if( url.indexOf('/') != -1 )
			{
				urls = url.substring( (url.indexOf('/')==0? 1: 0),url.lastIndexOf('/')).split('/');
			}
        }
        else{
			var si = url.indexOf('/', url.indexOf('://') + '://'.length);
			var ei = url.lastIndexOf( '/');
			if	( si < ei  ){
                urls = url.substring( si +1, ei).split('/');
			}
        }
        return urls;
    };

    TianvUtils.prototype.getDirName = function( url ){
        var urls = Utils.getDirs(url );
        if( !urls || urls.length<=1 )
            return null;

        if( urls[0].toLowerCase() == 'widgets' || urls[0].toLowerCase() == 'plugins' || urls[0].toLowerCase() == 'modules' || urls[0].toLowerCase() == 'channel' || urls[0].toLowerCase() == 'plugin'  )
            return urls[1];
        else
            return null;
    };

    TianvUtils.prototype.getSecondDirName = function( url ){

        var urls = Utils.getDirs(url );
        if( !urls || urls.length<=2 )
            return '';
            else
        return urls[2];
    }

    TianvUtils.prototype.getLastDirName = function( url ){
        var urls = Utils.getDirs(url );
        if( !urls || urls.length<=0 )
            return null;

        return urls[urls.length-1];
    };

})(jQuery);

(function($){

    String.prototype.htmlEncode = function () {
        if( this === null ) return this;
        return Utils.htmlEncode( this.toString() );
    };

    String.prototype.htmlDecode = function () {
        if( this === null ) return this;
        return Utils.htmlDecode( this.toString() );
    };

    String.prototype.format = function () {
        if( this === null ) return this;
        return Utils.stringFormat( this.toString(), arguments );
    };

})(jQuery);